<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VGroup>
          <el-select v-model="form.supplier.type" class="w-28">
            <el-option label="特采单号" value="psp_no"></el-option>
          </el-select>
          <VBatchInput v-model="form.supplier.value" @search="query" class="w-60" />
        </VGroup>
        <VGroup>
          <el-select v-model="form.skuInfo.type" class="w-28">
            <el-option label="sku" value="sku"></el-option>
            <el-option label="赛盒SKU" value="sai_he_sku"></el-option>
            <el-option label="自定义sku" value="custom_sku"></el-option>
          </el-select>
          <el-input v-model="form.skuInfo.value" placeholder="请输入" class="w-40"></el-input>
        </VGroup>
        <VSelect v-model="form.plan_type" :options="options.plan_type || []" style="min-width: 160px;" multiple collapse-tags filterable clearable placeholder="特采类型" />
        <VCascader v-model="form.create_user_id" placeholder="申请人员" multiple collapse-tags filterable clearable style="min-width: 160px" />
        <VCascader v-model="form.department_name" placeholder="申请部门" type="department" multiple collapse-tags filterable clearable style="min-width: 160px" />
        <VSelect v-model="form.audit_status" :options="options.audit_status || []" style="min-width: 160px;" multiple collapse-tags filterable clearable placeholder="审核状态" />
        <VSelect v-model="form.country_code" :options="options.country" style="min-width: 160px;" multiple collapse-tags filterable clearable placeholder="国家" />
        <VSelect v-model="form.plan_status" :options="options.plan_status || []" style="min-width: 160px;" multiple collapse-tags filterable clearable placeholder="计划状态" />
        <VCascader v-model="form.demand_sale" placeholder="负责销售" multiple collapse-tags filterable clearable style="min-width: 160px" />
        <VGroup>
          <el-select v-model="form.dateRange.type" class="w-28">
            <el-option label="申请日期" value="create_time"></el-option>
            <el-option label="审核日期" value="audit_time"></el-option>
          </el-select>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <VButton auth="/purchase/product/purchase/add" type="primary" @click="create(tableRef)"><i class="dk-iconfont icon-Plus" />添加
        </VButton>
        <VAudit
          :auth="['/purchase/product/purchase/purchaseAudit', '/purchase/product/purchase/oprateAudit', '/purchase/product/purchase/qaAudit', '/purchase/product/purchase/oprateCtoAudit', '/purchase/product/purchase/planConfirm']"
          field="psp_id" url="/v1/product/product-special-purchase/batch-audit" :tableRef="tableRef" :list="options.batch_audit_status" @success="query" />
        <VButton auth="/purchase/product/purchase/demand" @click="handleBatch('demand')">生成备库需求</VButton>
        <VImport auth="/purchase/product/purchase/batchimport" :tableRef="tableRef" importUrl="/v1/product/product-special-purchase/import"
          downloadUrl="https://xc-pms.oss-cn-shenzhen.aliyuncs.com/template/product_special_template.xlsx" class="ml-auto" @success="query" />
        <VExport auth="/purchase/product/purchase/derive" url="/v1/product/product-special-purchase/export" name="产品特采" :tableRef="tableRef" />
      </template>
    </VTable>
    <Add ref="addRef" :options="options" @success="query" />
    <VLog ref="logRef" />
  </VPage>
</template>
  
<script setup lang="jsx" name="Account">
import api from './api'
import Add from './components/Add'
import VImport from '@/components/VImport'
import { getOption, countrys } from '@/api/public'
import { ElMessage, ElMessageBox } from 'element-plus'
const baseName = 'special_purchase'
const tableRef = ref()
const logRef = ref()
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}

// 新增
const addRef = ref()
const create = () => {
  addRef?.value.open()
}

// 获取options
const options = ref({})
Promise.all([
  getOption({ type: baseName }).then(res => res.data),
  countrys().then(res => ({ countryOptions: res.data })),
  Promise.resolve({ test: [{ label: '没有数据', value: 1 }] })
]).then(res => {
  options.value = res.reduce((acc, cur) => (((acc = { ...acc, ...cur }), acc)), {})
})

// 批量操作
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning('请先选择行')
    return
  }
  const psp_ids = selection.map(d => d.psp_id)
  const showLoading = () => loadings[name] = true
  const closeLoading = () => loadings[name] = false
  const handle = {
    demand: (is_skip = 1) => {
      showLoading()
      api.demand({ psp_ids, is_skip }).then(res => {
        const { code, data, message } = res
        const { is_skip } = data
        if (code === 200) {
          ElMessage.success('生成成功')
          emit('success')
          close()
          return
        }
        if (is_skip === 2) {
          ElMessageBox.confirm(message, '提示', {
            type: 'error', confirmButtonText: '是',
            cancelButtonText: '否'
          }).then(res => {
            handle.demand(2)
          }).finally(() => {
            loadings[create + is_submit] = false
          })
        } else {
          ElMessage.error(message)
        }
      }).finally(() => {
        closeLoading()
      })
    },
  }
  handle[name]()
}
// 单行操作
const handleRow = (name, row, rowIndex) => {
  const { psp_id } = row
  const showLoading = () => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = () => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    look: () => {
      addRef?.value.open(psp_id, true)
    },
    edit: () => {
      addRef?.value.open(psp_id)
    },
    submit: () => {
      showLoading()
      api[name]({ psp_id }).then(res => {
        ElMessage({ type: 'success', message: '操作成功', })
        query()
      }).finally(() => {
        closeLoading()
      })
    },
    cancel: () => {
      ElMessageBox.confirm('是否确认作废？', '作废', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          api[name]({ psp_id }).then(res => {
            ElMessage({ type: 'success', message: '操作成功', })
            query()
          })
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
    confirm: () => {
      ElMessageBox.confirm('是否确认接收？', '计划确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          api.confirm({ psp_id }).then(res => {
            ElMessage({ type: 'success', message: '操作成功', })
            query()
          })
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
    back: () => {
      ElMessageBox.confirm('是否确认反审到待提交状态？', '反审', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      })
        .then(() => {
          api[name]({ psp_id }).then(res => {
            ElMessage({ type: 'success', message: '操作成功', })
            query()
          })
        })
        .catch(() => {
          ElMessage({ type: 'info', message: '取消操作', })
        })
    },
    log: () => {
      logRef?.value.open({ log_type: baseName, psp_id })
    }
  }
  handle[name]()
}

// 列表配置
const tableOptions = reactive({
  formConfig: {
    data: {
      supplier: { type: 'psp_no', value: '' }, // 组合
      skuInfo: { type: 'sku', value: '' }, // 组合
      dateRange: { type: 'create_time', value: [], range: true }, // 组合
    }
  },
  columns: [
    { type: 'checkbox', fixed: 'left', width: 40 },
    {
      title: '特采单', minWidth: 160, slots: {
        default: ({ row }) => {
          return <VText value={row.psp_no} type='link' onClick={() => handleRow('look', row)} />
        }
      }
    },
    { title: '特采类型', field: 'plan_type_name', minWidth: 100 },
    {
      title: '申请部门', field: 'apply_depart_name', minWidth: 120, slots: {
        default: ({ row }) => <VText value={row.apply_depart_name} line={2} />
      }
    },
    {
      title: '来源类型', field: 'source_type_name', minWidth: 100
    },
    {
      title: '申请人/申请日期', field: '', minWidth: 230, slots: {
        default: ({ row }) => < div >
          <VText title='申请人' value={row.create_user} line={1} />
          <VText title='申请人' value={row.create_time} line={1} />
        </div >
      }
    },
    {
      title: '审核状态/审核日期', field: '', minWidth: 230, slots: {
        default: ({ row }) => < div >
          <VText title='审核状态' value={row.audit_status_name} line={1} />
          <VText title='审核日期' value={row.audit_time} line={1} />
        </div >
      }
    },
    {
      title: '驳回原因', field: 'audit_remark', minWidth: 140, slots: {
        default: ({ row }) => <VText value={row.audit_remark} line={2} />
      }
    },
    { title: '计划状态', field: 'plan_status_name', minWidth: 140 },
    {
      field: 'remark', title: '备注', minWidth: 120, slots: {
        default: ({ row }) => <VText value={row.remark} line={2} />
      }
    },
    {
      title: '文件', width: 140, slots: {
        default: ({ row, rowIndex }) => {
          const files = row.files.filter(Boolean) || []
          if (!files?.length) return '-'
          const content = (line) => files.map(d => {
            const target = d.toLowerCase().indexOf('.pdf') > -1 ? '_blank' : '_self'
            return <a href={d} target={target} type="primary" class='w-full'><VText value={d} type='link' line={line} /></a>
          }) 
          return <VMore value={content} key={rowIndex} />
        }
      }
    },
    {
      title: '操作', width: 140, fixed: 'right', slots: {
        default: ({ row, rowIndex }) => {
          const { psp_id, audit_status } = row
          // audit_status 审核状态：1待提交2待采购审核3待运营审核4待质检审核5待运营总监审核6待计划确认7待生成计划需求单8已驳回9已审核10已作废
          return <div class='nm flex flex-wrap gap-x-2 gap-y-1'>
            <VButton auth="/purchase/product/purchase/view" link type="primary" onClick={() => handleRow('look', row)}>查看</VButton>
            {[1, 8].includes(audit_status) ? <VButton auth="/purchase/product/purchase/edit" link type="primary" onClick={() => handleRow('edit', row)}>编辑</VButton> : ''}
            {[1, 8].includes(audit_status) ? <VButton auth="/purchase/product/purchase/submit" link type="primary" loading={loadings['submit' + rowIndex]} onClick={() => handleRow('submit', row, rowIndex)}>提交</VButton> : ''}
            {[1, 8].includes(audit_status) ? <VButton auth="/purchase/product/purchase/void" link type="primary" onClick={() => handleRow('cancel', row)}>作废</VButton> : ''}
            {[9].includes(audit_status) ? <VButton auth="/purchase/product/purchase/countertrial" link type="primary" onClick={() => handleRow('back', row)}>反审</VButton> : ''}
            {[6].includes(audit_status) ? <VButton auth="/purchase/product/purchase/planConfirm" link type="primary" onClick={() => handleRow('confirm', row)}>计划确认</VButton> : ''}
            <VButton auth="/purchase/product/purchase/logs" link type="primary" onClick={() => handleRow('log', row)}>日志</VButton>
          </div>
        }
      }
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => api.query({ ...form, ...page })
    }
  }
})
</script>
  